const axios = require('axios');


const baseurl = 'http://127.0.0.1:5000'

const fire = require('js-fire')
var parserDate = function (date) { 
	var t = Date.parse(date); 
	if (!isNaN(t)) { 
		return new Date(Date.parse(date.replace(/-/g, "/"))); 
	} else { 
		return new Date(); 
	} 
};


const CURDER = {}

class timetable {
	constructor(api){
		this.api = api
	}
	create(name,status){
		CURDER.create(this.api,{name,status})
	},
	change(id,name,time,status){
		CURDER.update(this.api,id,{time,status})
	},
	list(page,per_page){
		CURDED.colget(this.api,{page,per_page})
	}
	delete(id,name,time,status){
		CURDER.delete(this.api,id,{name,time,status})
	}
	get(id){
		CURDER.get(this.api,id)
	}
}

const record ={
	__description__: 'To note the record',
	create: (name,time= new Date(),status) =>{
		if (typeof(time)=='string'){
			time = parserDate(time)
		}
		axios.post(api+'/records',
					{'name':name,
						'time': time.getTime(),
						'status':status,
					}).then((res)=>{ console.log('添加成功')})
						.catch( (error)=> {console.log('添加失败'+error)})

	},
	list:(page=1,per_page=100) => {
		axios.get(api+'/records',{
						params:{'page':page,
						'per_page':per_page,
					}}).then(response => (response.data.map( item => {console.log(item)})))
						.catch( (error)=> {console.log('查询失败'+error)})
	},
	change: (id,name,time,status) =>{
		time = parserDate(time).getTime()
		axios.put(api+'/record/'+id,
					{'name':name,
						'time': time,
						'status':status,
					})
					.then((res)=>{ console.log('修改成功')})
					.catch((err)=>{ console.log('修改失败'+err)})
	},
	delete: (id) =>{
		axios.delete(api+'/record/'+id)
					.then((res)=>{ console.log('删除成功')})
					.catch((err)=>{ console.log('删除失败'+err)})
	},
	mark: (name,period,time = new Date()) => {
		if (typeof(time)=='string'){
			time = parserDate(time)
		}
		time_end = time
		time_begin = new Date(time - period*60*60*1000)
		record.create(name,time_begin,'开始')
		record.create(name,time_end,'结束')
	},
}


const tag = {
	create: (name,description) =>{
		axios.post(api+'/tag',
						{'name':name,
						'description':description
					}).then((res)=>{ console.log('添加成功')})
						.catch( (error)=> {console.log('添加失败'+error)})
	}
}


const clockin = {	
}

const timetable = timetable(baseurl+'/timetable')
const task = {}

const cli = {
	record,
	tag,
	clockin,
	timetable,
	task
}
fire(cli)
//fire(tag)
